package com.hula.onion.book.server.spider.platforms.edspay;

import com.alibaba.fastjson.JSONObject;
import com.hula.onion.book.server.common.CommonResponse;
import com.hula.onion.book.server.common.SpiderCommon;
import com.hula.onion.book.server.config.ResponseStatusEnum;
import com.hula.onion.book.server.utils.CookieUtils;
import com.hula.onion.book.server.utils.HttpUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.client.protocol.HttpClientContext;
import org.apache.http.impl.cookie.BasicClientCookie;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import sun.misc.BASE64Decoder;

import java.io.IOException;

/**
 * Description:E都市钱包
 * Create Date:2018/1/30 19:33
 *
 * @author liangbing
 * @version 1.0
 */
@Component("eDSPaySpider")
public class EDSPaySpider extends SpiderCommon {

    /**
     * 登录页面URL
     */
    private static final String LOGIN_PAGE_URL = "https://www.edspay.com";

    /**
     * 登录URL
     */
    private static final String LOGIN_URL = "https://sso.edspay.com/user/doLogin";

    /**
     * 验证码URL
     */
    private static String CAPTCHA_URL = "https://rest.edspay.com/validimg";

    /**
     * 获取账户信息URL
     */
    private static final String GET_ACCOUNT_INFO_URL = "https://rest.edspay.com/account/basic";

    @Autowired
    private EDSPaySpiderHelper spiderHelper;

    /**
     * 执行爬取操作
     * 1.获取 RSA key
     * 2.组装模拟登陆参数，模拟登陆
     * 3.爬取用户详细信息
     */
    @Override
    public CommonResponse execute() {
        //1. 从缓存中获取cookie，设置到cookie store中
        CookieUtils.setCookie(loginForm.getPlatformId(), loginForm.getUserId(), getHttpContext().getCookieStore());

        //模拟登陆
        String loginStr = HttpUtils.post(LOGIN_URL,
                spiderHelper.installRequestParams(loginForm),
                getHttpContext());
        if (StringUtils.isEmpty(loginStr)) {
            return new CommonResponse(ResponseStatusEnum.FAIL);
        }
        logger.info("[EDSPaySpider] Http response result:{}", loginStr);
        //登陆成功
        if (JSONObject.parseObject(loginStr).getBoolean("success")) {
            // 爬取数据
            String json = HttpUtils.post(GET_ACCOUNT_INFO_URL,
                    spiderHelper.installLoginRequestParams(JSONObject.parseObject(loginStr).getString("token")),
                    getHttpContext());
            return spiderHelper.parseAccountBalance(json);

        } else {
            CommonResponse commonResponse = new CommonResponse(ResponseStatusEnum.ACCOUNT_ERROR);
            commonResponse.setMsg(JSONObject.parseObject(loginStr).getString("resMsg"));
            return commonResponse;
        }

    }

    @Override
    public String getCaptchaURL() {
        return CAPTCHA_URL;
    }

    @Override
    public String getLoginPageURL() {
        return LOGIN_PAGE_URL;
    }


    /**
     * 直接获取验证码
     */
    public byte[] getCheckCode(HttpClientContext httpClientContext) {
        String jsonStr = HttpUtils.post(CAPTCHA_URL, null, httpClientContext);
        if (StringUtils.isNotEmpty(jsonStr)) {
            boolean result = JSONObject.parseObject(jsonStr).getBoolean("success");
            if (result) {
                String s = JSONObject.parseObject(jsonStr).getJSONObject("resData").getString("validCode");
                String captchaId = JSONObject.parseObject(jsonStr).getJSONObject("resData").getString("captchaId");
                BasicClientCookie cookie = new BasicClientCookie("captchaId", captchaId);
                cookie.setDomain("");
                cookie.setPath("");
                httpClientContext.getCookieStore().addCookie(cookie);
                String imgCode = StringUtils.substringAfter(s, "data:image/jpeg;base64,");
                BASE64Decoder decoder = new BASE64Decoder();
                // 解密
                try {
                    byte[] b = decoder.decodeBuffer(imgCode);
                    // 处理数据
                    for (int i = 0; i < b.length; ++i) {
                        if (b[i] < 0) {
                            b[i] += 256;
                        }
                    }
                    return b;
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return null;
    }
}

